package com.fr71.project.dm.utils;

import com.fr71.common.utils.spring.SpringUtils;
import com.fr71.project.dm.service.IPdOrderService;
import com.fr71.project.dm.service.IPdUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TimerTask;

public class DMUtils {
    private static final Set<String> existingCDKs = new HashSet<>();
    private static final String source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final Random random = new Random();

    private static final Logger logger = LoggerFactory.getLogger(DMUtils.class);

    private static IPdUserService userService;
    private static IPdOrderService orderService;

    private static IPdUserService getUserService() {
        if (userService == null) {
            userService = SpringUtils.getBean(IPdUserService.class);
        }
        return userService;
    }

    private static IPdOrderService getOrderService() {
        if (orderService == null) {
            orderService = SpringUtils.getBean(IPdOrderService.class);
        }
        return orderService;
    }

    //插件启动时调用一次
    public static void onJarStart() {
        //将所有的安全码加入到临时维护的列表 防止生成重复的
        getUserService().selectPdUserList(null).forEach(user -> {
            if (!existingCDKs.contains(user.getSCode())) {
                existingCDKs.add(user.getSCode());
            }
        });
        
        getOrderService().selectPdOrderList(null).forEach(order -> {
            if (!existingCDKs.contains(order.getsCode())) {
                existingCDKs.add(order.getsCode());
            }
        });

        logger.debug("安全码库填充完成,已使用CDK数量：{}", existingCDKs.size());
    }

    public static String generateUniqueSafCode() {
        String newCDK;
        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                sb.append(source.charAt(random.nextInt(source.length())));
            }
            newCDK = sb.toString();
        } while (existingCDKs.contains(newCDK));

        existingCDKs.add(newCDK);
        return newCDK;
    }

    public static void removeKey(String code) {
        existingCDKs.remove(code);
    }

    private static final String publicKey =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoGwOQDS8MLav6aVbaJOJkeVnqQiChu7Q5ypAVDZs7LeQrRj9B5+/88YUaFvmB6QiKROYwnAeJ8GxNoZXeigdgm4zxvEUMH8y2dkjJjwXDCVH1Y7o6J2Yx8tLoEW52ysRzIENqYxXASgekPXn0AHWCDdDK/MDe1+2p+fabXqWBQwIDAQAB";
    private static final String privateKey =
            "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKgbA5ANLwwtq/ppVtok4mR5WepCIKG7tDnKkBUNmzst5CtGP0Hn7/zxhRoW+YHpCIpE5jCcB4nwbE2hld6KB2CbjPG8RQwfzLZ2SMmPBcMJUfVjujonZjHy0ugRbnbKxHMgQ2pjFcBKB6Q9efQAdYIN0Mr8wN7X7an59ptepYFDAgMBAAECgYBJskYWkeENSrx5dFLSIZdqitTDYSgjH0H8j/QodqWWBSFhY1N6Fi9cyZkbffT2Ye4Ph/MOXmjjrRYd1nf4brSajNJYr0eegDsnfK6osk0ejkrjVDIGi/ZFEAg77Y6QIrM3MruQG5EsWGaFppfwFHVwTE+Fy7d4FFR3QkWBraaUGQJBANBfOSMFLumYZrVyh+GcvvaNpGEHd06714kPVhnIvI38CNAzixes2jSch+8R4BE6A9/itxVVnFARyJfk28dXYF0CQQDOh57ww1q7SCOquG484m2VrA6nv5OKwYdKk1JVE2N1Uvhp5Rh6s+ox8PWt60Zs3vrl8h8+nLjwzH7/o9mZPs4fAkB9rKECbTLhMsjnsP8hZO+MNtuopd8gfoy9nqFYhcirfhI2uI+wpNEqoCogV9CjszD5DH1OAcd4R3GLoz2nGh0FAkA7DmTQi8wCCZrJUnuTRVv4lH6MUSerYbOCC6ZbVXP3NIZ8IVpim9e3+CMIXGKC9y/fWOC+Uqo/kPovt3adb2wZAkBLjuKLrzn+htJskFben/5qL0YVpJorEqU9jPdpGBSnPCZ/dFTFbTmFw/Txv4w2skN75qbBaDaxcyu9B9PDy6Kk";

    // 获取真实IP
    public static String getRealIp(HttpServletRequest request) {
        String realIp = request.getHeader("x-real-ip");
        return realIp != null ? realIp : request.getRemoteAddr();
    }

    // 字符串加密
    public static String encrypt(String text) {
        try {
            return RsaUtils.encryptByPrivateKey(privateKey, text);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 运行任务
    public static TimerTask runTask(TaskFactroy factory, Runnable invoke) {
        return new TimerTask() {
            @Override
            public void run() {
                invoke.run();
            }
        };
    }

}